package conexion;

import elementos.Ranking;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ConectarRanking implements ConexionServidorRanking{
    
    public URLConnection getConnection(){
        try {
            String location = "http://localhost:8080/web/ScoreServlet";
            URL url = new URL(location);
            URLConnection connection = url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setRequestProperty("Content-Type", "application/x-java-serialized-object");
            return connection;
        } catch (IOException ex) {
            Logger.getLogger(ConectarRanking.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    @Override
    public Ranking saveScore(String id, float score,int level) {
        OutputStream outstream = null;
        try {
            URLConnection connection = getConnection();
            outstream = connection.getOutputStream();
            ObjectOutputStream sout = new ObjectOutputStream(outstream);
            sout.writeObject(id);
            sout.writeObject(score);
            sout.writeObject(level);
            sout.flush();
            sout.close();
            
            InputStream instream = connection.getInputStream();
            ObjectInputStream sin = new ObjectInputStream(instream);
            Ranking ranking;
            ranking = (Ranking) sin.readObject();
            sin.close();
            return ranking;
        } catch (Exception ex) {
            Logger.getLogger(ConectarRanking.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        } finally {
            try {
                outstream.close();
            } catch (IOException ex) {
                Logger.getLogger(ConectarRanking.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
}
